﻿namespace EyeOpen.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using EyeOpen.Domain;
    using EyeOpen.Queries;

    public abstract class BaseDataContext : IDataContext
    {
        public abstract IEnumerable<TResult> GetByQuery<TSource, TResult>(IQuery<TSource, TResult> query);
        
        public virtual IEnumerable<TResult> GetByQuery<TSource, TResult>(IQuery<TSource, TResult> query, int pageIndex, int pageSize)
        {
            if (pageIndex < 1)
            {
                throw new ArgumentOutOfRangeException("pageIndex");
            }

            if (pageSize < 1)
            {
                throw new ArgumentOutOfRangeException("pageSize");
            }

            return
                GetByQuery(query)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
        }

        public abstract void BeginTransaction();

        public abstract void Commit();

        public abstract void Rollback();

        public abstract void SaveChanges();

        public abstract void Dispose();

        public void ExecuteInTransaction(Action action)
        {
            BeginTransaction();

            try
            {
                action.Invoke();
                Commit();
            }
            catch (Exception ex)
            {
                Rollback();
                throw new DataException("DataContext error. See inner exception for details.", ex);
            }
        }
                                                                                                                
        protected virtual void Save(UniqueEntity entity)
        {
            CheckEntity(entity);
        }

        protected void CheckEntity(UniqueEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id == Guid.Empty)
            {
                var message =
                    string.Format(
                        "Cannot save an entity with empty key (\"{{00000000-0000-0000-0000-000000000000}}\". Entity type \"{0}\".",
                        entity.GetType().Name);

                throw new ArgumentException(message, "entity");
            }
        }
    }
}